/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ts } from 'qvog-dsl';
import {
  native,
  HomeCheckHint,
} from 'qvog-dsl';

const SEVERITY = 2;
const DOC_PATH = 'docs/no-unsafe-authentication-dsl.md';
const DESCRIPTION = 'Authentication issues arise from design or implementation flaws in authentication mechanisms. These issues may allow attackers to bypass authentication or impersonate other users.';

const sensitiveKeywords = ['password', 'passwd', 'pwd'];

export default native<HomeCheckHint>()()
  .match((node): node is ts.CallExpression => {
    return ts.isCallExpression(node);
  })
  .when((node: ts.CallExpression) => {
    if (!ts.isPropertyAccessExpression(node.expression)) { return false };

    const expr = node.expression;
    const caller = expr.expression.getText();
    const method = expr.name.getText();

    const unsafeCall = caller === 'logger' && ['info', 'warn', 'error'].includes(method)
    || caller === 'res' && ['send', 'json'].includes(method);
    if (!unsafeCall) { return false };
    

    // include key information
    for (const arg of node.arguments) {
      if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg)) {
        const text = arg.text.toLowerCase();
        if (sensitiveKeywords.some(keyword => text.includes(keyword))) {
          return true;
        }
      }
    }

    return false;
  })
  .report({
    severity: SEVERITY,
    description: DESCRIPTION,
    docPath: DOC_PATH,
  });
